package cn.bocai.pc.web.portal;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeUtility;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.bocai.pc.model.BcCollect;
import cn.bocai.pc.model.BcUser;
import cn.bocai.pc.service.BcCollectService;
import cn.bocai.pc.service.BcUserService;
import cn.bocai.pc.util.DataUtils;
import cn.bocai.pc.util.MD5Utils;
import cn.bocai.pc.util.UUIDUtils;


@Controller
@RequestMapping("/result")
public class ResultController {
	@Autowired
	private BcCollectService bcCollectService;
   @Autowired
	private BcUserService userService;
   
   
	//用户注册信息保存
     @RequestMapping(value="/register")
     public String doPost(HttpServletRequest request, HttpServletResponse response,BcUser bu,Model m) { 
         String validateC = (String) request.getSession().getAttribute("validateCode"); 
         String veryCode = request.getParameter("securityCode");
         m.addAttribute("skipUrl","/skip/register.do");
         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 m.addAttribute("msg","验证码不能为空");
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
            	 String selectName = userService.selectEmail(bu.getEmail());
            	 if("1".equals(selectName)){
            		 m.addAttribute("msg",bu.getEmail()+"已存在");
            	 }else if("0".equals(selectName)){
            		 bu.setUserId(UUIDUtils.getUUID32());
                	 bu.setUsername(bu.getUsername());
                	 bu.setPassword(MD5Utils.md5(bu.getPassword()));
                	 bu.setEmail(bu.getEmail());
                	 bu.setRegisterTime(DataUtils.now());
                	 bu.setRegisterIp(getIpAddr(request,response));
                	 int register = userService.insertRegister(bu);
                	 if(!"0".equals(register)){
                	   m.addAttribute("msg","注册成功,请登入");
                	   m.addAttribute("skipUrl","/skip/login.do");
                	 }
            	 }
             }else{        
                 m.addAttribute("msg","输入验证码有误");
             }        
         }        
         return "bcPage/prompt/publicPrompt";
     }        

     //用户登入
     @RequestMapping("/doLogin")
     public String doLogin(HttpServletRequest request, HttpServletResponse response,BcUser logbu,Model m){
         String validateC = (String) request.getSession().getAttribute("validateCode"); 
         String veryCode = request.getParameter("securityCode");
         m.addAttribute("skipUrl","/skip/login.do");
         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 m.addAttribute("msg","验证码不能为空");
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
            	 publicLogin(request,logbu,m,"page");
             }else{        
                 m.addAttribute("msg","输入验证码有误");
             }        
         }        
        return "bcPage/prompt/publicPrompt";
     }
     
     //用户头部右上角登入
     @RequestMapping("/headLogin")
     public String headLogin(HttpServletRequest request, HttpServletResponse response,BcUser logbu,Model m){
        publicLogin(request,logbu,m,"head");
         return "bcPage/prompt/publicPrompt";
     }
     
     //用户安全退出
     @RequestMapping("/dologout")
       public String dologout(HttpServletRequest request){
    	 request.getSession().removeAttribute("selectLogin");
  		return "bcPage/accounts/login";
       }
     
     //用户注册的时候输入用户名进行ajax校验用户名是否已存在
     @RequestMapping("/AjaxName")
       public void  AjaxName(HttpServletRequest request, HttpServletResponse response) throws IOException{
    	 response.setContentType("text/html;charset=utf-8");  
    	 String name = request.getParameter("c");
    	 PrintWriter out = response.getWriter();
    	 String selectName = userService.selectNameExist(name);
    	 if("1".equals(selectName)){
    		 out.println("已被注册");   
    	 }else if("0".equals(selectName)){
    		 out.println("可以使用");   
    	 }
         out.flush();        
         out.close();
       }
     
     @RequestMapping("/sendingEmail")
     public String sendingEmail(HttpServletRequest request, HttpServletResponse response,String userName,String email,Model m){
    	 BcUser users = userService.findUserByName(userName);
    	 m.addAttribute("msg","用户名或者邮箱有误!");
    	 m.addAttribute("skipUrl","/skip/forgetPwd.do");
    	 if(users!=null&&users.getEmail().equals(email)){
	         String validateC = (String) request.getSession().getAttribute("validateCode"); 
	         String veryCode = request.getParameter("securityCode");
	         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
	        	 m.addAttribute("msg","验证码不能为空");
	         }else{        
	             if(validateC.equalsIgnoreCase(veryCode)){
	            	 String msg="";
	            	 try{  
	            	        String secretKey= UUID.randomUUID().toString();  //密钥  
	            	        Timestamp outDate = new Timestamp(System.currentTimeMillis()+30*60*1000);//30分钟后过期  
	            	        long date = outDate.getTime()/1000*1000;                  //忽略毫秒数  
	            	        
	            	        users.setValidatacode(secretKey);//将秘钥进行保存
	            	        users.setRegisterDate(outDate);//设置的秘钥过期时间
	            	        userService.updateByPrimaryKeySelective(users);    //保存到数据库  
	            	        
	            	        String key = users.getUsername()+"$"+date+"$"+secretKey;  
	            	        String digitalSignature = MD5Utils.md5(key);
	            	  
	            	        String emailTitle = "九龙图库网站账户密码重置";  
	            	        String path = request.getContextPath();  
	            	        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
	            	        String resetPassHref =  basePath+"result/reset_password.do?sid="+digitalSignature+"&userName="+users.getUsername();  
	            	        String emailContent = "您在九龙图库网站使用了密码重置功能, 请通过下面的地址修改密码:"+resetPassHref+" 本邮件超过30分钟,链接将会失效，需要重新申请";
	            	        /*System.out.print(resetPassHref); */ 
	            	        /*SendMail.getInstatnce().sendHtmlMail(emailTitle,emailContent,users.getEmail());*/  
	            	        sendHtmlMail(emailTitle,emailContent,users);
	            	        msg = "操作成功,已经发送找回密码链接到您邮箱。请在30分钟内重置密码!";  
	            	    }catch (Exception e){  
	            	        e.printStackTrace();  
	            	        msg="未知错误,还是联系管理员吧!";  
	            	    }  
	            	 m.addAttribute("msg",msg);
	            	 
	             }else{        
	                 m.addAttribute("msg","输入验证码有误!");
	             }
	         }
         }        
         return "bcPage/prompt/publicPrompt";
     }
     //邮件发送的配置代码
     public void sendHtmlMail(String emailTitle,String emailContent,BcUser users) throws MessagingException, UnsupportedEncodingException{  
         Properties props = new Properties();  
         // 开启debug调试  
         props.setProperty("mail.debug", "true");  
         // 发送服务器需要身份验证  
         props.setProperty("mail.smtp.auth", "true");  
         // 设置邮件服务器主机名  
         props.setProperty("mail.host", "smtp.qq.com");  
         //设置主机端口
         props.setProperty("mail.smtp.port", "587");
         // 发送邮件协议名称  
         props.setProperty("mail.transport.protocol", "smtp");  
         // 设置环境信息  
         Session session = Session.getInstance(props);  
         // 创建邮件对象  
         Message msg = new MimeMessage(session);  
         //主题
         msg.setSubject(emailTitle);  
         // 设置邮件内容  
         msg.setText(emailContent);
         
         //设置邮件收件人中文名称转换防止出现乱码
         String recipients = MimeUtility.encodeText(users.getUsername()); 
         // 设置收件人 
         msg.setRecipient(RecipientType.TO, new InternetAddress(recipients+"<"+users.getEmail()+">")); 
         
         //设置邮件发件人中文名称转换防止出现乱码
         String nick = MimeUtility.encodeText("九龙图库邮件通知中心"); 
         // 设置发件人  
         msg.setFrom(new InternetAddress(nick+"<2783903047@qq.com>")); 
         // 保存并生成最终的邮件内容 
         msg.saveChanges();   
         Transport transport = session.getTransport();  
         // 连接邮件服务器  
         transport.connect("2783903047@qq.com", "9330264851flb");  
        /* transport.connect("smtp.qq.com", 587, "xxxxx@qq.com", "xxxxxx");*/
         // 发送邮件  
         transport.sendMessage(msg, new Address[] {new InternetAddress(users.getEmail())});  
         // 关闭连接  
         transport.close();  
     }  
     
     //重置密码判断
     @RequestMapping(value = "/reset_password",method = RequestMethod.GET)  
        public String checkResetLink(String sid,String userName,Model m) throws UnsupportedEncodingException{ 
	    	 m.addAttribute("msg","链接错误,无法找到值,请重新申请找回密码.");
	    	 m.addAttribute("skipUrl","/skip/forgetPwd.do");
	    	 String returnadd="bcPage/prompt/publicPrompt";
	    	 String fileName = new String(userName.getBytes("ISO-8859-1"), "UTF-8");//将get传输的数据进行转码
			 BcUser users = userService.findUserByName(fileName);//获取数据库中的值
			 if(users!= null){
				 Timestamp outDate = users.getRegisterDate();//获取之前存入数据库的时间
				 if(outDate!= null){
					 String key = users.getUsername()+"$"+outDate.getTime()/1000*1000+"$"+users.getValidatacode();          //数字签名 
					 String digitalSignature = MD5Utils.md5(key);
		            if(!sid.equals("") && !fileName.equals("")&&users!= null&&digitalSignature.equals(sid)){  
		            	if(outDate.getTime() <= System.currentTimeMillis()){         //表示已经过期  
		                  m.addAttribute("msg","链接已经过期,请重新申请找回密码.");
		                }else{
		       			 m.addAttribute("users",users);
		                 returnadd= "bcPage/accounts/resetPassword";//如果验证成功直接跳转回去
		                }  
		            }
				 } 
			 }
            return returnadd;
        }  
     
    //登入以后修改密码
     @RequestMapping("/doModifyPwd")
     public String doModifyPwd(HttpServletRequest request, HttpServletResponse response,Model m){
         String validateC = (String) request.getSession().getAttribute("validateCode"); //获取验证码
         String oldPaw =MD5Utils.md5(request.getParameter("password")) ;
    	 String newPaw =MD5Utils.md5(request.getParameter("newPwd"));
         String veryCode = request.getParameter("securityCode");
         m.addAttribute("skipUrl","/skip/afterLogin/alterPassword.do");
         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 m.addAttribute("msg","验证码不能为空");
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
            	 BcUser attribute = (BcUser)request.getSession().getAttribute("selectLogin");
            	 String password = attribute.getPassword();
            	 if(!password.equals(oldPaw)){
            		 m.addAttribute("msg","输入密码有误");
            	 }else{
            		 HashMap<String, Object> map = new HashMap<String, Object>();
            		 map.put("userId", attribute.getUserId());
            		 map.put("password", newPaw);
            		 int updateUserPaw = userService.updateUserPaw(map);
            		 if(!"0".equals(updateUserPaw)){
            			 request.getSession().removeAttribute("selectLogin");
            			 m.addAttribute("msg","密码修改成功");
            			 m.addAttribute("skipUrl","/skip/login.do");
            		 }
            	 }
             }else{        
                 m.addAttribute("msg","输入验证码有误");
             }        
         }        
         return "bcPage/prompt/publicPrompt";
     }
     
     
   //重置密码
     @RequestMapping("/resetModifyPwd")
     public void resetModifyPwd(HttpServletRequest request, HttpServletResponse response,Model m,BcUser users) throws IOException{
    	 String validateC = (String) request.getSession().getAttribute("validateCode"); //获取session中的验证码
         String veryCode = request.getParameter("securityCode");//获取前台传输过来的验证码
         PrintWriter out=response.getWriter();
         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 /*m.addAttribute("msg","验证码不能为空");*/
        	 out.print("null");//表示验证码为空
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
            	 BcUser selectBcUser = userService.selectByPrimaryKey(users.getUserId());//根据前段隐藏的id查询出该条数据
            	 
            	 selectBcUser.setPassword(MD5Utils.md5(users.getPassword()));//密码加密
            	 selectBcUser.setValidatacode(null);//将秘钥设置为null
            	 selectBcUser.setRegisterDate(null);//将过期时间设置为null
            	 
            	 int updateUserPaw = userService.updateByPrimaryKey(selectBcUser);
            	 if(!"0".equals(updateUserPaw)){
            		 out.print("1");//修改成功
        		 }else{
        			 out.print("0");//修改失败
        		 }
             }else{        
            	 out.print("erro");//验证码错误
             }        
         }        
     }
     
     /**
 	 * 收藏页面的ajax请求，保存收藏的数据
 	 * @author chenhao
 	 * @throws ParseException 
 	 * @time 2015/07/07
 	 */
 	@RequestMapping("/sonInstallThumId.do")
 	public void sonInstallThumId(HttpServletRequest request, HttpServletResponse response,BcCollect record,Model m){
 		BcUser attribute = (BcUser)request.getSession().getAttribute("selectLogin");
 		PrintWriter out=null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
 		
 		if(null!=attribute){
			String uuid = request.getParameter("uuid");
			String periods = request.getParameter("periods");
			String colour =request.getParameter("colour");
			String year = request.getParameter("year");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id",attribute.getUserId());
			map.put("thumpId",uuid);
			map.put("year",year);
			map.put("periods",periods);
			//先去查询数据库是否有改值
			BcCollect queryEstimate = bcCollectService.queryEstimate(map);
			if(null==queryEstimate){
				//judges传过来的值是add就是添加，如果传过来的是del就删除	
		    	Date date=new Date(); 
		    	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		    	String format = dateFormat.format(date);
		    	record.setId(UUIDUtils.getUUID32());
		 		record.setBcUserId(attribute.getUserId());
		 		record.setColYear(year);
		 		record.setColTime(format);
		 		record.setColPictype("1");
		 		record.setRemarks1(uuid);
		 		if(!"".equals(periods)){
		 		record.setColPeriods(periods);	
		 		}
		 		record.setColour(colour);
		 		int insert = bcCollectService.insert(record);
		 		if(1 ==insert){
		 		 out.print("success");
		 		}else{
		 		 out.print("defeated");
		 		}
			}else{
				 out.print("already");
			}
		}else{
			out.print("no");//表示未登入
		}
 	}
     
//到客户端查询用户的ip地址
     private String getIpAddr(HttpServletRequest request, HttpServletResponse response) {   
          String ipAddress = null;   
          //ipAddress = this.getRequest().getRemoteAddr();   
          ipAddress = request.getHeader("x-forwarded-for");   
          if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
           ipAddress =request.getHeader("Proxy-Client-IP");   
          }   
          if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
              ipAddress = request.getHeader("WL-Proxy-Client-IP");   
          }   
          if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
           ipAddress = request.getRemoteAddr();   
           if(ipAddress.equals("127.0.0.1")){   
            //根据网卡取本机配置的IP   
            InetAddress inet=null;   
         try {   
          inet = InetAddress.getLocalHost();   
         } catch (UnknownHostException e) {   
          e.printStackTrace();   
         }   
         ipAddress= inet.getHostAddress();   
           }   
                 
          }   
       
          //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割   
          if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15   
              if(ipAddress.indexOf(",")>0){   
                  ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));   
              }   
          }   
          return ipAddress;    
       } 

     /**
  	 * 模板页面会员收藏校验
  	 * @author chenhao
  	 */
  	@RequestMapping("/collectTemplate.do")
  	public void collectTemplate(HttpServletRequest request, HttpServletResponse response,Model m){
  		BcUser attribute = (BcUser)request.getSession().getAttribute("selectLogin");
  		PrintWriter out=null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
  		if(null!=attribute){
  			 out.print("1");
  		}else{
  			out.print("0");
  		}
     }
     //用户登入的公共方法
     public void publicLogin(HttpServletRequest request,BcUser logbu,Model m,String judge){
    	 if("".equals(logbu.getUsername())||null==logbu.getUsername()||"".equals(logbu.getPassword())||null==logbu.getPassword()){
    		 m.addAttribute("msg","用户名或密码不能为空");
    		 if("page".equals(judge)){
    			 m.addAttribute("skipUrl","/skip/login.do");
     		  }else{
     			 m.addAttribute("skipUrl","/skip/login.do");
     		  }
    	 }else{
    		 logbu.setPassword(MD5Utils.md5(logbu.getPassword()));
        	 BcUser selectLogin = userService.selectLogin(logbu);
        	 if(null==selectLogin){
        		 m.addAttribute("msg","用户名或密码错误");
        		 if("page".equals(judge)){
        			 m.addAttribute("skipUrl","/skip/login.do");
         		  }else{
         			 m.addAttribute("skipUrl","/skip/login.do");
         		  }
                 
        	 }else{
        		 m.addAttribute("msg","登入成功，谢谢！");
        		 request.getSession().setAttribute("selectLogin", selectLogin);
        		 m.addAttribute("skipUrl","/skip/afterLogin/afLoCollect.do");
        	 }
          }
     }
}
